import {defineStore} from 'pinia';
import {Login, GetUserInfo} from "@/api/user.js"

const useUserInfo = defineStore('userInfo', {
    state: () => {
        return {
            userInfo: {},
            token: undefined,
            webSocket: null,
            onLineList: []
        }
    },
    persist: { // 自定义持久化方式
        storage: window.localStorage,
        beforeHydrate: context => {
            console.log('Before', context)
        },
        afterHydrate(context) {
            console.log('After', context)
            GetUserInfo().then((res) => {
                context.store.userInfo = res.data
            })
        }
    },
    getters: {
        getToken() {
            return this.token
        },
    },
    actions: {

        // 登录操作
        async login(params) {
            const res = await Login(params)
            this.token = res.data
            await this.getUserInfo()
        },
        // 获取用户信息
        async getUserInfo() {
            const res = await GetUserInfo()
            this.userInfo = res.data
        },
        // 退出登录操作
        logout() {
            if (this.webSocket) {
                this.webSocket.close()
            }
            this.userInfo = {}
            this.token = undefined

        },
    }
});
export default useUserInfo
